package com.sxbdjw.situation.core;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;

import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import com.gwsd.GWPttApi;
import com.gwsd.GWPttEngine;
import com.gwsd.GWVideoEngine;
import com.gwsd.audio.IGWPttAudioModule;
import com.gwsd.bean.GWChatGroupDetailBean;
import com.gwsd.bean.GWCurrentGroupNotifyBean;
import com.gwsd.bean.GWDuplexBean;
import com.gwsd.bean.GWGroupListBean;
import com.gwsd.bean.GWGroupOperateBean;
import com.gwsd.bean.GWJoinGroupBean;
import com.gwsd.bean.GWKickoutNotifyBean;
import com.gwsd.bean.GWLoginResultBean;
import com.gwsd.bean.GWMemberInfoBean;
import com.gwsd.bean.GWMsgBean;
import com.gwsd.bean.GWRequestSpeakBean;
import com.gwsd.bean.GWSpeakNotifyBean;
import com.gwsd.bean.GWTempGroupBean;
import com.gwsd.bean.GWTempGroupNotifyBean;
import com.gwsd.bean.GWType;
import com.gwsd.rtc.view.GWRtcSurfaceVideoRender;
import com.sxbdjw.situation.activity.AudioCallActivity;
import com.sxbdjw.situation.activity.VideoCallActivity;
import com.sxbdjw.situation.activity.VideoViewActivity;
import com.sxbdjw.situation.core.config.DeviceConfig;
import com.sxbdjw.situation.core.config.ServerAddressConfig;
import com.sxbdjw.situation.core.domain.ExitTmpGroupEventBean;
import com.sxbdjw.situation.core.domain.GWPttUserInfo;
import com.sxbdjw.situation.core.domain.OfflineEventBean;
import com.sxbdjw.situation.plugins.IntercomPlugin;
import com.sxbdjw.situation.utils.ScreenWakeUtils;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;


public class GWSDKManager implements GWPttApi.GWPttObserver, GWVideoEngine.GWVideoEventHandler, Handler.Callback {

    private Context context;
    private GWPttEngine gwPttEngine;
    private GWVideoEngine gwVideoEngine;
    protected HandlerThread handlerThread;
    protected Handler handler;

    private GWPttUserInfo userInfo;
    private String imei;
    private String iccid;

    private Disposable disposable;

    private GWSDKPttEngineObserver pttObserver;

    public void onBtnVoiceCall(int convId, String convName) {
        AudioCallActivity.startAct(this.context, convId, convName, true);
    }

    public void onBtnVideoCall(Integer convId, String convName) {
        VideoCallActivity.startAct(this.context, String.valueOf(convId), convName, true, false);
    }

    public void getLocation() {

        LocationManager manager = (LocationManager) this.context.getSystemService(Context.LOCATION_SERVICE);


        //2、获取有效的provider，并显示出来
        List<String> providerlist = manager.getAllProviders();

        if (ActivityCompat.checkSelfPermission(this.context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this.context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }

        manager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5 * 1000, 0, new LocationListener() {
            @Override
            public void onLocationChanged(@NonNull Location location) {
                IntercomPlugin.getPlugin().sendMsg(300001, JSON.toJSONString(new HashMap<>() {{
                    put("lat", location.getLatitude());
                    put("lon", location.getLongitude());
                }}));
            }
        });
        Location locate = manager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        if (locate != null) {
            log("当前位置：" + locate.getLatitude() + "  " + locate.getLongitude());

            IntercomPlugin.getPlugin().sendMsg(300001, JSON.toJSONString(new HashMap<>() {{
                put("lat", locate.getLatitude());
                put("lon", locate.getLongitude());
            }}));
        }
    }

    public interface GWSDKPttEngineObserver {
        void onPttEvent(int var1, String var2, int var3);

        void onMsgEvent(int var1, String var2);
    }

    public interface GWSDKVideoEngineObserver extends GWVideoEngine.GWVideoEventHandler {

    }

    private static GWSDKManager gwsdkManager;

    public static GWSDKManager INSTANCE(Context context) {
        if (gwsdkManager == null) {
            synchronized (GWSDKManager.class) {
                if (gwsdkManager == null) {
                    gwsdkManager = new GWSDKManager(context);
                }
            }
        }
        return gwsdkManager;
    }

    public static GWSDKManager getSdkManager() {
        return gwsdkManager;
    }

    public boolean isOnline() {
        return userInfo.isOnline();
    }
    private void log(String msg) {
        Log.i("GWSD", this.getClass().getSimpleName() + "=" + msg);
    }

    public Context getContext() {
        return context;
    }

    private GWSDKManager(Context context) {
        this.context = context;
        gwPttEngine = GWPttEngine.INSTANCE(this.context);
        CallManager.INSTANCE(this.context);
        gwVideoEngine = GWVideoEngine.INSTANCE();
        gwPttEngine.pttInit(this, this, null);
        gwPttEngine.pttConfigServer(0, ServerAddressConfig.PTT_SERVER_ADDRESS, ServerAddressConfig.PTT_SERVER_PORT);
        gwPttEngine.pttConfigServer(1, ServerAddressConfig.MSG_SERVER_ADDRESS, ServerAddressConfig.MSG_SERVER_PORT);
        gwPttEngine.pttConfigServer(2, ServerAddressConfig.DISPATCH_SERVER_ADDRESS, ServerAddressConfig.DISPATCH_SERVER_PORT);
        gwPttEngine.pttConfigServer(3, ServerAddressConfig.VIDEO_SERVER_ADDRESS, ServerAddressConfig.VIDEO_SERVER_PORT);
        log("current sdk version:" + gwPttEngine.pttGetVersion());
        userInfo = new GWPttUserInfo();
        handlerThread = new HandlerThread("SDKManagerThread");
        handlerThread.start();
        handler = new Handler(handlerThread.getLooper(), this);

    }

    // 登录
    public void login(String account, String password) {
        log("执行登录");
        login(account, password, DeviceConfig.getDeviceImei(), DeviceConfig.getDeviceIccid());
    }

    private final int LOGIN_AGAIN_MSG = 0;

    @Override
    public boolean handleMessage(@NonNull Message msg) {
        switch (msg.what) {
            case LOGIN_AGAIN_MSG:
                log("login msg try login");
                login(userInfo.getAccount(), userInfo.getPassword(), imei, iccid);
                break;
            default:
                break;
        }
        return false;
    }

    /**
     * 登录
     *
     * @param account
     * @param password
     * @param imei
     * @param iccid
     */
    public void login(String account, String password, String imei, String iccid) {
        gwPttEngine.pttLogin(account, password, imei, iccid);
        this.imei = imei;
        this.iccid = iccid;
        userInfo.setAccount(account);
        userInfo.setPassword(password);
        userInfo.setOnline(false);
    }


    public void registerPttObserver(GWSDKPttEngineObserver observer) {
        pttObserver = observer;
    }


    private Map<Long, GWGroupListBean.GWGroupBean> groupMap;
    // 群组列表
    private List<GWGroupListBean.GWGroupBean> groupBeanList;
    // 用户列表
    private List<GWMemberInfoBean.MemberInfo> memBeanList;
    private boolean haveStartMsgService = false;

    private GWJoinGroupBean currentgwJoinGroupBean;

    @Override
    public void onPttEvent(int event, String data, int data1) {
        log("onPttEvent ptt event=" + event + " data=" + data);
        Gson gson = new Gson();
        // 登录事件
        if (event == GWType.GW_PTT_EVENT.GW_PTT_EVENT_LOGIN) {

            GWLoginResultBean gwLoginResultBean = gson.fromJson(data, GWLoginResultBean.class);
            if (gwLoginResultBean.getResult() == 0) {
                log(gwLoginResultBean.getName() + " login success");
                userInfo.setName(gwLoginResultBean.getName());
                userInfo.setId(gwLoginResultBean.getUid());
                userInfo.setOnline(true);
                userInfo.setDefaultGid(gwLoginResultBean.getDefaultGid());
                userInfo.setMessage(gwLoginResultBean.isMessage());
                userInfo.setCall(gwLoginResultBean.isCall());
                userInfo.setVideo(gwLoginResultBean.isVideo());
                userInfo.setSilent(gwLoginResultBean.isSilent());
                gwPttEngine.pttHeart(DeviceConfig.getDeviceBattery(), DeviceConfig.getDeviceNetwork(), System.currentTimeMillis());
                startTimer();
                queryGroup();
                //joinGroup(gwLoginResultBean.getDefaultGid(), 0);
            }
            removeSDKHandlerMessage(LOGIN_AGAIN_MSG);
        } else if (event == GWType.GW_PTT_EVENT.GW_PTT_EVENT_QUERY_GROUP) {
            log("recv query group event" + data);
            // 查询群组
            GWGroupListBean gwGroupListBean = gson.fromJson(data, GWGroupListBean.class);
            if (gwGroupListBean.getResult() == 0) {
                List<GWGroupListBean.GWGroupBean> groups = gwGroupListBean.getGroups();
                if (groupMap == null) {
                    groupMap = new HashMap<>();
                }
                if (groupBeanList == null) {
                    groupBeanList = new ArrayList<>();
                }
                groupMap.clear();
                groupBeanList.clear();
                groupBeanList.addAll(groups);
                for (GWGroupListBean.GWGroupBean gwGroupBean : groupBeanList) {
                    if (gwGroupBean.getType() != GWType.GW_MSG_RECV_TYPE.GW_PTT_MSG_RECV_TYPE_SELFGROUP) {
                        gwGroupBean.setType(GWType.GW_MSG_RECV_TYPE.GW_PTT_MSG_RECV_TYPE_GROUP);
                    }
                }
                int[] msg_groups = new int[groups.size()];
                int[] msg_groups_type = new int[groups.size()];
                int i = 0;
                long joingroupid = 0;
                int joingrouptype = 0;
                for (GWGroupListBean.GWGroupBean group : groups) {
                    if (group.getGid() == userInfo.getDefaultGid()) {
                        joingroupid = group.getGid();
                        joingrouptype = group.getType();
                    }
                    groupMap.put(group.getGid(), group);
                    msg_groups[i] = (int) group.getGid();
                    msg_groups_type[i] = group.getType();
                    i++;
                }
                if (userInfo.isMessage() || userInfo.isVideo() || userInfo.isSilent()) {
                    startMsgService(msg_groups, msg_groups_type, groups.size());
                }
                if (joingroupid == 0) {
                    joingroupid = groups.get(0).getGid();
                    joingrouptype = groups.get(0).getType();
                }
                if (userInfo.getCurrentGroupGid() == 0) {
                    joinGroup(joingroupid, joingrouptype);
                }

            }
        } else if (event == GWType.GW_PTT_EVENT.GW_PTT_EVENT_JOIN_GROUP) {
            log("recv join group event" + data);
            // 进去群组
            GWJoinGroupBean gwJoinGroupBean = gson.fromJson(data, GWJoinGroupBean.class);
            currentgwJoinGroupBean = gwJoinGroupBean;
            if (gwJoinGroupBean.getResult() == 0) {
                userInfo.setCurrentGroupGid(gwJoinGroupBean.getGid());
                userInfo.setCurrentGroupPriority(gwJoinGroupBean.getPriority());
                userInfo.setLastpriority(userInfo.getCurrentGroupPriority());
                userInfo.setCurrentGroupName(groupMap.get(gwJoinGroupBean.getGid()).getName());
                userInfo.setCurrentGroupType(groupMap.get(gwJoinGroupBean.getGid()).getType());
            }

        } else if (event == GWType.GW_PTT_EVENT.GW_PTT_EVENT_QUERY_MEMBER) {
            // 查询用户
            GWMemberInfoBean gwMemberInfoBean = gson.fromJson(data, GWMemberInfoBean.class);
            if (gwMemberInfoBean.getResult() == 0) {
                List<GWMemberInfoBean.MemberInfo> members = gwMemberInfoBean.getMembers();
                if (memBeanList == null) {
                    memBeanList = new ArrayList<>();
                }
                memBeanList.clear();
                memBeanList.addAll(members);
                IntercomPlugin.getPlugin().sendMsg(GWType.GW_PTT_EVENT.GW_PTT_EVENT_QUERY_MEMBER, JSON.toJSONString(members));
            }
        } else if (event == GWType.GW_PTT_EVENT.GW_PTT_EVENT_REQUEST_MIC) {
            // 请求麦克风
            GWRequestSpeakBean gwRequestSpeakBean = gson.fromJson(data, GWRequestSpeakBean.class);
        } else if (event == GWType.GW_PTT_EVENT.GW_PTT_EVENT_TMP_GROUP_ACTIVE) {
            GWTempGroupBean gwTempGroupBean = gson.fromJson(data, GWTempGroupBean.class);
        } else if (event == GWType.GW_PTT_EVENT.GW_PTT_EVENT_TMP_GROUP_PASSIVE) {
            GWTempGroupNotifyBean gwTempGroupNotifyBean = gson.fromJson(data, GWTempGroupNotifyBean.class);
//            if (gwTempGroupNotifyBean.getName() != null && gwTempGroupNotifyBean.getName() != "") {
//                CallManager.getManager().checkCallStateSwitch(CallManager.CALL_STATE_PTT_TMP_GROUP_CALL, (notice, caninterrupt, currentstate, nextstate) -> {
//                    if (caninterrupt) {
//                        PttCallActivity.startAct(AppManager.getApp(), gwTempGroupNotifyBean.getUid(), gwTempGroupNotifyBean.getName(), GWType.GW_MSG_RECV_TYPE.GW_PTT_MSG_RECV_TYPE_USER ,false);
//                    } else {
//                        int[] ids = new int[1];
//                        ids[0] = 0;
//                        tempGroup(ids, 1);
//                    }
//                });
//            } else {
//                log("remote releas tmp group");
//            }
        } else if (event == GWType.GW_PTT_EVENT.GW_PTT_EVENT_DUPLEX) {
            GWDuplexBean gwDuplexBean = gson.fromJson(data, GWDuplexBean.class);
            if (gwDuplexBean.getResult() == 0) {
                if (gwDuplexBean.getStatus() == GWType.GW_DUPLEX_STATUS.GW_PTT_DUPLEX_STATUS_INVIET) {
                    if (gwDuplexBean.getUid() != 0) {
                        CallManager.getManager().checkCallStateSwitch(CallManager.CALL_STATE_AUDIO_VIDEO_CALL, (notice, caninterrupt, currentstate, nextstate) -> {
                            if (notice) {
                                ScreenWakeUtils.getInstace(AppManager.getApp()).openScreenAndUnLockOnly(true);
//                                NotifiDataBean notifiDataBean = new NotifiDataBean();
//                                notifiDataBean.setRecvNm(gwDuplexBean.getName());
//                                notifiDataBean.setRecvId(gwDuplexBean.getUid());
//                                notifiDataBean.setType(NotifiDataBean.NOTIFI_TYPE_AUDIO_CALL);
//                                MainService.startServerWithData(AppManager.getApp(), notifiDataBean);
                            } else {
                                if (caninterrupt) {
                                    if (currentstate == CallManager.CALL_STATE_PTT_TMP_GROUP_CALL) {
                                        EventBus.getDefault().post(new ExitTmpGroupEventBean());
                                        Observable.timer(500, TimeUnit.MILLISECONDS)
                                                .observeOn(AndroidSchedulers.mainThread())
                                                .subscribe(aLong -> {
                                                    AudioCallActivity.startAct(AppManager.getApp(), gwDuplexBean.getUid(), gwDuplexBean.getName(), false);
                                                });
                                    } else {
                                        AudioCallActivity.startAct(AppManager.getApp(), gwDuplexBean.getUid(), gwDuplexBean.getName(), false);
                                    }
                                } else {
                                    // need notice
//                                    NotifiDataBean notifiDataBean = new NotifiDataBean();
//                                    notifiDataBean.setRecvNm(gwDuplexBean.getName());
//                                    notifiDataBean.setRecvId(gwDuplexBean.getUid());
//                                    notifiDataBean.setType(NotifiDataBean.NOTIFI_TYPE_AUDIO_CALL);
//                                    notifiDataBean.setForceNotice(true);
//                                    MainService.startServerWithData(AppManager.getApp(), notifiDataBean);
                                }
                            }
                        });
                    }
                } else if (gwDuplexBean.getStatus() == GWType.GW_DUPLEX_STATUS.GW_PTT_DUPLEX_STATUS_END) {
                    if (CallManager.getManager().getCallState() != CallManager.CALL_STATE_AUDIO_VIDEO_CALL) {
//                        NotifiDataBean notifiDataBean = new NotifiDataBean();
//                        notifiDataBean.setType(NotifiDataBean.NOTIFI_TYPE_CALL_END);
//                        notifiDataBean.setForceNotice(true);
//                        MainService.startServerWithData(AppManager.getApp(), notifiDataBean);
                    }
                }
            }

        } else if (event == GWType.GW_PTT_EVENT.GW_PTT_EVENT_LOGOUT) {
            log("logout");
            offline(OfflineEventBean.OFFLINE_REASON_LOGOUT_CODE, null);
        } else if (event == GWType.GW_PTT_EVENT.GW_PTT_EVENT_KICKOUT) {
            GWKickoutNotifyBean gwKickoutNotifyBean = gson.fromJson(data, GWKickoutNotifyBean.class);
            log("kickout");
            offline(OfflineEventBean.OFFLINE_REASON_KICKOUT_CODE, gwKickoutNotifyBean.getReason());
        } else if (event == GWType.GW_PTT_EVENT.GW_PTT_EVENT_CURRENT_GROUP) {
            GWCurrentGroupNotifyBean gwCurrentGroupNotifyBean = gson.fromJson(data, GWCurrentGroupNotifyBean.class);
            if (gwCurrentGroupNotifyBean.getResult() == 0) {
                userInfo.setCurrentGroupGid(gwCurrentGroupNotifyBean.getGid());
                userInfo.setCurrentGroupName(gwCurrentGroupNotifyBean.getName());
                userInfo.setCurrentGroupType(0);
                if (gwCurrentGroupNotifyBean.getReason().equals("return")) {
                    userInfo.setCurrentGroupPriority(userInfo.getLastpriority());
                } else {
                    userInfo.setLastpriority(userInfo.getCurrentGroupPriority());
                    userInfo.setCurrentGroupPriority(-1);
                }
            }
        } else if (event == GWType.GW_PTT_EVENT.GW_PTT_EVENT_SPEAK) {
            GWSpeakNotifyBean gwSpeakNotifyBean = gson.fromJson(data, GWSpeakNotifyBean.class);
            IntercomPlugin.getPlugin().sendMsg(event, data);
        } else if (event == GWType.GW_PTT_EVENT.GW_PTT_EVENT_PLAY_DATA) {
            log("recv pcm data=" + data1);
            return;
        } else if (event == GWType.GW_PTT_EVENT.GW_PTT_EVENT_LOSTMIC) {
            log("speak too long time stop record");
        } else if (event == GWType.GW_PTT_EVENT.GW_PTT_EVENT_GROUP_OPERATE) {
            GWGroupOperateBean gwGroupOperateBean = gson.fromJson(data, GWGroupOperateBean.class);
        } else if (event == GWType.GW_PTT_EVENT.GW_PTT_EVENT_QUERY_DISPATCH) {
            GWMemberInfoBean gwMemberInfoBean = gson.fromJson(data, GWMemberInfoBean.class);
        } else if (event == GWType.GW_PTT_EVENT.GW_PTT_EVENT_FRIEND_OPERATE) {
            GWMemberInfoBean gwMemberInfoBean = gson.fromJson(data, GWMemberInfoBean.class);
        } else if (event == GWType.GW_PTT_EVENT.GW_PTT_EVENT_QUERY_CHAT_GRP) {
            GWGroupListBean gwGroupListBean = gson.fromJson(data, GWGroupListBean.class);
        } else if (event == GWType.GW_PTT_EVENT.GW_PTT_EVENT_CHAT_GRP_DETAIL) {
            GWChatGroupDetailBean gwChatGroupDetailBean = gson.fromJson(data, GWChatGroupDetailBean.class);
        } else {
            log("error happen");
            offline(OfflineEventBean.OFFLINE_REASON_ERROR_CODE, null);
        }
        if (pttObserver != null) {
            pttObserver.onPttEvent(event, data, data1);
        }
    }

    public void mutePttSpk(boolean mute) {
        int open = mute ? 0 : 1;
        gwPttEngine.pttVoiceToggle(0, open);
    }

    public void mutePttMic(boolean mute) {
        int open = mute ? 0 : 1;
        gwPttEngine.pttVoiceToggle(1, open);
    }

    public void fullDuplex(int uid, int action) {
        gwPttEngine.pttDuplexCall(uid, action);
    }

    public void sendGroup() {
        IntercomPlugin.getPlugin().sendMsg(GWType.GW_PTT_EVENT.GW_PTT_EVENT_QUERY_GROUP, JSON.toJSONString(groupBeanList));
        IntercomPlugin.getPlugin().sendMsg(GWType.GW_PTT_EVENT.GW_PTT_EVENT_JOIN_GROUP, groupMap.get(currentgwJoinGroupBean.getGid()).getName());
    }


    private void startTimer() {
        disposable = Observable.interval(50, TimeUnit.SECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(aLong -> {
                    //Log.d(TAG, "send heart");
                    gwPttEngine.pttHeart(DeviceConfig.getDeviceBattery(), DeviceConfig.getDeviceNetwork(), System.currentTimeMillis());
                });
    }


    private void stopTimer() {
        if (disposable != null && !disposable.isDisposed()) {
            disposable.dispose();
            disposable = null;
        }
    }

    private boolean autoLogin = true;

    private void offline(int code, String info) {
        userInfo.setOnline(false);
        stopTimer();
        haveStartMsgService = false;
        EventBus.getDefault().post(new OfflineEventBean(code, info));
        if (code != OfflineEventBean.OFFLINE_REASON_LOGOUT_CODE) {
            if (autoLogin) {
                log("other login kickout login again");
                sendMessageToSDKHandler(LOGIN_AGAIN_MSG, 3000);
            }
        }
    }

    private void sendMessageToSDKHandler(int msg, int timeout) {
        handler.sendEmptyMessageDelayed(msg, timeout);
    }

    /**
     * 加入群组
     *
     * @param gid
     * @param type
     */
    public void joinGroup(long gid, int type) {
        gwPttEngine.pttJoinGroup(gid, type);
    }

    public void startMsgService(int groups[], int type[], int num) {
        if (!haveStartMsgService) {
            gwPttEngine.pttRegOfflineMsg(groups, type, num, (char) 0);
            haveStartMsgService = true;
        }
    }

    public void queryGroup() {
        gwPttEngine.pttQueryGroup();
    }

    private void removeSDKHandlerMessage(int msg) {
        handler.removeMessages(msg);
    }


    public void startSpeak() {
        gwPttEngine.pttSpeak(GWType.GW_SPEAK_TYPE.GW_PTT_SPEAK_START, System.currentTimeMillis());
    }

    public void stopSpeak() {
        gwPttEngine.pttSpeak(GWType.GW_SPEAK_TYPE.GW_PTT_SPEAK_END, System.currentTimeMillis());
    }

    public void sendMsg(String msg) {
//        createMsgBean()
    }

    public GWPttUserInfo getUserInfo() {
        return userInfo;
    }

    public void callVideo(String remoteid, boolean record, GWVideoEngine.GWVideoResolution resolution) {
        if (!userInfo.isOnline()) {
            log("user not login!!!");
            return;
        }
        gwVideoEngine.videoCall(userInfo.getAccount(), String.valueOf(userInfo.getId()), userInfo.getName(), remoteid, record, resolution);
    }

    public void attachRemoteVideoView(GWRtcSurfaceVideoRender render, long userid) {
        gwVideoEngine.videoAttachRemoteView(render, userid);
    }

    public void attachLocalVideoView(GWRtcSurfaceVideoRender render) {
        gwVideoEngine.videoAttachLocalView(render);
    }

    public void switchCamera() {
        gwVideoEngine.switchCamera();
    }

    public void acceptCallVideo() {
        if (!userInfo.isOnline()) {
            log("user not login!!!");
            return;
        }
        gwVideoEngine.videoAcceptCall(userInfo.getAccount(), String.valueOf(userInfo.getId()), userInfo.getName());
    }

    public void muteMic(boolean mute) {
        gwVideoEngine.muteMic(mute);
    }

    public void muteSpk(boolean mute) {
        gwVideoEngine.muteSpeaker(mute);
    }

    public GWMsgBean createMsgBean(int recvtype, int remoteid, String remoteNm, int msgtype) {
        GWMsgBean gwMsgBean = new GWMsgBean();
        gwMsgBean.setFrom(String.valueOf(userInfo.getId()));
        gwMsgBean.setType(msgtype);
        long tm = System.currentTimeMillis();
        gwMsgBean.setTime((int) (tm / 1000));
        GWMsgBean.MsgContent msgContent = new GWMsgBean.MsgContent();
        msgContent.setContent("");
        msgContent.setSendId(String.valueOf(userInfo.getId()));
        msgContent.setSendName(userInfo.getName());
        msgContent.setSendUType(GWType.GW_MSG_RECV_TYPE.GW_PTT_MSG_RECV_TYPE_USER);
        msgContent.setReceiveId(String.valueOf(remoteid));
        msgContent.setReceiveName(remoteNm);
        msgContent.setReceiveUType(recvtype);
        msgContent.setTime((int) (tm / 1000));
        msgContent.setMsgType(msgtype);
        gwMsgBean.setData(msgContent);
        return gwMsgBean;
    }

    public void sendMsg(GWMsgBean msg) {
        String content = msg.getData().getContent();
        long ts = (long) msg.getTime() * 1000;
        if (msg.getType() != GWType.GW_MSG_TYPE.GW_PTT_MSG_TYPE_TEXT) {
            content = msg.getData().getUrl();
        }
        log(msg.toString());
        gwPttEngine.pttSendMsg(userInfo.getId(), userInfo.getName(), msg.getData().getReceiveUType(), Integer.valueOf(msg.getData().getReceiveId()),
                msg.getData().getReceiveName(), msg.getType(), content, msg.getData().getThumbUrl(), 0, "", (char) 0, ts, (char) 1, (char) 1);
    }

    public String createThumb(String video) {
        String thumb = gwPttEngine.pttCreateThumbForVideo(video);
        log("thumb=" + thumb);
        return thumb;
    }


    private GWSDKVideoEngineObserver videoObserver;

    public void registerVideoObserver(GWSDKVideoEngineObserver observer) {
        videoObserver = observer;
    }

    public void clearVideoView(GWRtcSurfaceVideoRender render) {
        gwVideoEngine.videoClearView(render);
    }

    public void hangupVideo(String remoteid) {
        if (!userInfo.isOnline()) {
            log("user not login!!!");
            return;
        }
        gwVideoEngine.videoHangup(String.valueOf(userInfo.getId()), userInfo.getName(), remoteid);
    }

    @Override
    public void onMsgEvent(int i, String s) {
        log("onMsgEvent :  event=" + i + " data=" + s);
        IntercomPlugin.getPlugin().sendMsg(GWType.GW_PTT_EVENT.GW_PTT_EVENT_CHAT_MSG_DETAIL, s);

    }


    @Override
    public void onVideoEvent(String s) {

    }

    public void acceptPullVideo(int cameraNum, boolean virtualCamera) {
        if (!userInfo.isOnline()) {
            log("user not login!!!");
            return;
        }
        gwVideoEngine.videoAcceptPull(userInfo.getAccount(), String.valueOf(userInfo.getId()), userInfo.getName(), cameraNum, virtualCamera);
    }

    public void pullVideo(String remoteid, boolean silent, boolean record, GWVideoEngine.GWVideoPriority priority, GWVideoEngine.GWVideoResolution resolution) {
        if (!userInfo.isOnline()) {
            log("user not login!!!");
            return;
        }
        gwVideoEngine.videoPull(String.valueOf(userInfo.getId()), userInfo.getName(), remoteid, silent, record, priority, resolution);
    }

    @Override
    public void onVideoPull(String remoteid, String remotenm, int remotetype, boolean silent) {
        if (videoObserver != null) {
            videoObserver.onVideoPull(remoteid, remotenm, remotetype, silent);
        }
        if (silent) {
            if (CallManager.getManager().getCallState() < CallManager.CALL_STATE_AUDIO_VIDEO_CALL) {
                acceptPullVideo(2, false);
            } else {
                log("device is busy");
            }
        } else {
            ScreenWakeUtils.getInstace(AppManager.getApp()).openScreenAndUnLockOnly(true);
            CallManager.getManager().checkCallStateSwitch(CallManager.CALL_STATE_AUDIO_VIDEO_CALL, ((notice, caninterrupt, currentstate, nextstate) -> {
                if (notice) {
                    ScreenWakeUtils.getInstace(AppManager.getApp()).openScreenAndUnLockOnly(true);
//                    NotifiDataBean notifiDataBean = new NotifiDataBean();
//                    notifiDataBean.setRecvNm(remotenm);
//                    notifiDataBean.setRecvIdStr(remoteid);
//                    notifiDataBean.setRecord(false);
//                    notifiDataBean.setType(NotifiDataBean.NOTIFI_TYPE_VIDEO_PULL);
//                    MainService.startServerWithData(AppManager.getApp(), notifiDataBean);
                } else {
                    if (caninterrupt) {
                        if (currentstate == CallManager.CALL_STATE_PTT_TMP_GROUP_CALL) {
                            EventBus.getDefault().post(new ExitTmpGroupEventBean());
                            Observable.timer(500, TimeUnit.MILLISECONDS)
                                    .observeOn(AndroidSchedulers.mainThread())
                                    .subscribe(aLong -> {
                                        VideoViewActivity.startAct(AppManager.getApp(), remoteid, remotenm, false, false);
                                    });
                        } else {
                            VideoViewActivity.startAct(AppManager.getApp(), remoteid, remotenm, false, false);
                        }
                    } else {
                        // need notice
//                        NotifiDataBean notifiDataBean = new NotifiDataBean();
//                        notifiDataBean.setRecvNm(remotenm);
//                        notifiDataBean.setRecvIdStr(remoteid);
//                        notifiDataBean.setRecord(false);
//                        notifiDataBean.setType(NotifiDataBean.NOTIFI_TYPE_VIDEO_PULL);
//                        notifiDataBean.setForceNotice(true);
//                        MainService.startServerWithData(AppManager.getApp(), notifiDataBean);
                    }
                }
            }));
        }
    }

    @Override
    public void onVideoCall(String s, String s1) {
        if (videoObserver != null) {
            videoObserver.onVideoCall(s, s1);
        }
        CallManager.getManager().checkCallStateSwitch(CallManager.CALL_STATE_AUDIO_VIDEO_CALL, (notice, caninterrupt, currentstate, nextstate) -> {
            if (notice) {
                ScreenWakeUtils.getInstace(AppManager.getApp()).openScreenAndUnLockOnly(true);
//                NotifiDataBean notifiDataBean = new NotifiDataBean();
//                notifiDataBean.setRecvNm(s1);
//                notifiDataBean.setRecvIdStr(s);
//                notifiDataBean.setRecord(false);
//                notifiDataBean.setType(NotifiDataBean.NOTIFI_TYPE_VIDEO_CALL);
//                MainService.startServerWithData(AppManager.getApp(), notifiDataBean);
            } else {
                if (caninterrupt) {
                    if (currentstate == CallManager.CALL_STATE_PTT_TMP_GROUP_CALL) {
                        EventBus.getDefault().post(new ExitTmpGroupEventBean());
                        Observable.timer(500, TimeUnit.MILLISECONDS)
                                .observeOn(AndroidSchedulers.mainThread())
                                .subscribe(aLong -> {
                                    VideoCallActivity.startAct(AppManager.getApp(), s, s1, false, false);
                                });
                    } else {
                        VideoCallActivity.startAct(AppManager.getApp(), s, s1, false, false);
                    }
                } else {
                    // need notice
//                    NotifiDataBean notifiDataBean = new NotifiDataBean();
//                    notifiDataBean.setRecvNm(s1);
//                    notifiDataBean.setRecvIdStr(s);
//                    notifiDataBean.setRecord(false);
//                    notifiDataBean.setType(NotifiDataBean.NOTIFI_TYPE_VIDEO_CALL);
//                    notifiDataBean.setForceNotice(true);
//                    MainService.startServerWithData(AppManager.getApp(), notifiDataBean);
                }
            }
        });
    }

    @Override
    public void onVideoMeetingInvite(String s, String s1) {

    }

    @Override
    public void onVideoMeetingCancel() {

    }

    @Override
    public void onVideoMeetingSpeak() {

    }

    @Override
    public void onVideoMeetingMute() {

    }

    @Override
    public void onVideoMeetingUserJoin(long l, String s, String s1, boolean b) {

    }

    @Override
    public void onVideoMeetingSelfJoin() {

    }

    @Override
    public void onVideoMeetingUserLeave(long l) {

    }

    @Override
    public void onVideoMeetingKickout() {

    }

    @Override
    public void onLocalStreamReady() {
        if (videoObserver != null) {
            videoObserver.onLocalStreamReady();
        }
    }

    @Override
    public void onRemoteStreamReady(boolean b, long l) {
        if (videoObserver != null) {
            videoObserver.onRemoteStreamReady(b, l);
        }

    }

    @Override
    public void onRemoteStreamRemove() {
        if (videoObserver != null) {
            videoObserver.onRemoteStreamRemove();
        }
    }

    @Override
    public void onLocalStreamRemove() {
        if (videoObserver != null) {
            videoObserver.onLocalStreamRemove();
        }
    }

    @Override
    public void onVideoData(byte[] bytes, int i, int i1, int i2, int i3) {
        if (videoObserver != null) {
            videoObserver.onVideoData(bytes, i, i1, i2, i3);
        }
    }

    @Override
    public void onHangup(String s) {
        if (videoObserver != null) {
            videoObserver.onHangup(s);
        }
        if (CallManager.getManager().getCallState() != CallManager.CALL_STATE_AUDIO_VIDEO_CALL) {
//            NotifiDataBean notifiDataBean = new NotifiDataBean();
//            notifiDataBean.setType(NotifiDataBean.NOTIFI_TYPE_CALL_END);
//            notifiDataBean.setForceNotice(true);
//            MainService.startServerWithData(AppManager.getApp(), notifiDataBean);
        }
    }

    @Override
    public void onError(int i, String s) {
        if (videoObserver != null) {
            videoObserver.onError(i, s);
        }
    }
}
